<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElContainer, ElHeader, ElAside, ElMain, ElMenu, ElMenuItem, ElSubMenu, ElAvatar, ElDropdown, ElDropdownMenu, ElDropdownItem, ElIcon, ElRow, ElCol, ElButton } from 'element-plus'
import { User as UserIcon, SwitchButton, Setting, HomeFilled, Document, DataLine, Calendar } from '@element-plus/icons-vue'
import { menuItems, menuTitles } from './config/menuConfig.js'

const route = useRoute()

const router = useRouter()
const username = ref('')
const activeMenu = ref('/home') // 使用实际的路径作为初始值
const collapsed = ref(false)

// 详细的路由状态监控
const debugRouteState = () => {
  const currentRoute = router.currentRoute.value
  console.log('=== 路由状态调试 ===')
  console.log('当前路径:', currentRoute.path)
  console.log('当前名称:', currentRoute.name)
  console.log('活动菜单:', activeMenu.value)
  console.log('匹配路径:', router.resolve(currentRoute.path).resolvedLocation)
  console.log('=====================')
}

onMounted(() => {
  // 从localStorage获取用户名
  username.value = localStorage.getItem('username') || '用户'
  // 初始化当前活动菜单项
  updateInitialMenu()
  
  // 监听路由变化，确保在路由切换时更新活动菜单
  router.afterEach((to, from) => {
    console.log('路由afterEach:', from.path, '->', to.path)
    
    // 延迟执行确保路由完全更新
    setTimeout(() => {
      debugRouteState()
      syncActiveMenu()
    }, 100) // 增加到100ms确保路由更新完成
  })
  
  // 初始调试
  setTimeout(() => {
    debugRouteState()
  }, 500)
})

// 根据当前路径设置初始活动菜单
const updateInitialMenu = () => {
  const currentPath = router.currentRoute.value.path
  console.log('初始化当前路径:', currentPath)
  
  if (currentPath === '/' || currentPath === '/login') {
    activeMenu.value = '/home'
  } else {
    activeMenu.value = currentPath
  }
  
  console.log('初始活动菜单:', activeMenu.value)
}

// 监听当前路由变化来同步活动菜单状态
watch(() => route.path, (newPath, oldPath) => {
  console.log('路径watch变化:', oldPath, '->', newPath)
  // 如果路径确实改变了，更新活动菜单
  if (newPath !== oldPath) {
    if (newPath === '/' || newPath === '/login') {
      activeMenu.value = '/home'
    } else {
      activeMenu.value = newPath
    }
  }
}, { immediate: false }) // 移除immediate避免重复执行

// 监听路由变化来更新活动菜单
const syncActiveMenu = () => {
  const path = router.currentRoute.value.path
  console.log('路由变化，更新活动菜单:', path)
  
  // 更新活动菜单
  activeMenu.value = path
  
  // 如果没有匹配到，设置为首页
  if (!activeMenu.value || activeMenu.value === '/' || activeMenu.value === '/login') {
    activeMenu.value = '/home'
  }
}

const handleLogout = () => {
  // 清除登录状态
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('username')
  ElMessage.success('已退出登录')
  router.push('/login')
}

const handleMenuClick = (index) => {
  console.log('=== 菜单点击 ===')
  console.log('点击的菜单项:', index)
  console.log('当前路径:', router.currentRoute.value.path)
  console.log('当前活动菜单:', activeMenu.value)
  
  // 如果点击的就是当前路径，不执行任何操作
  if (router.currentRoute.value.path === index) {
    console.log('已经是当前页面，无需跳转')
    return
  }
  
  // 更新活动菜单
  activeMenu.value = index
  
  // 执行路由跳转
  router.push(index).then((res) => {
    console.log('路由跳转完成:', index, res)
  }).catch(err => {
    console.error('路由跳转失败:', err)
    ElMessage.error(`跳转失败: ${err.message}`)
  })
}

const getMenuTitle = (index) => {
  // 直接查找菜单标题映射
  if (menuTitles[index]) {
    return menuTitles[index]
  }
  
  // 如果是路径形式，从路径中提取
  if (index.startsWith('/')) {
    const routeIndex = index.substring(1) // 去掉前导斜杠
    return menuTitles[routeIndex] || index
  }
  
  return menuTitles[index] || index
}

const toggleSidebar = () => {
  collapsed.value = !collapsed.value
}
</script>

<template>
  <el-container class="app-container">
    <!-- 顶部导航栏 -->
    <el-header height="60px" class="app-header">
      <el-row class="header-content">
        <el-col :span="12">
          <div class="header-left">
            <el-button 
              icon="el-icon-menu" 
              circle 
              plain 
              @click="toggleSidebar"
              class="sidebar-toggle"
            />
            <h1 class="logo-text">
              <el-icon><HomeFilled /></el-icon>
              管理系统
            </h1>
          </div>
        </el-col>
        <el-col :span="12" class="header-right">
          <div class="header-actions">
            <el-button icon="el-icon-bell" circle plain />
            <el-button icon="el-icon-message" circle plain />
            <el-dropdown placement="bottom">
              <span class="user-info">
                <el-avatar :size="36" icon="el-icon-user" />
                <span class="username">{{ username }}</span>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-icon><UserIcon /></el-icon>
                    <span>个人信息</span>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-icon><Setting /></el-icon>
                    <span>设置</span>
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon>
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
    </el-header>
    
    <el-container class="main-container">
      <!-- 左侧菜单栏 -->
      <el-aside :width="collapsed ? '64px' : '240px'" class="app-sidebar" :class="{ 'collapsed': collapsed }">
        <el-menu 
          :default-active="activeMenu" 
          class="sidebar-menu" 
          mode="vertical" 
          @select="handleMenuClick"
          :collapse="collapsed"
          background-color="#001529"
          text-color="#fff"
          active-text-color="#409EFF"
          :router="false"
        >
          <!-- 动态渲染菜单 -->
          <template v-for="item in menuItems" :key="item.index">
            <!-- 子菜单 -->
            <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.index">
              <template #title>
                <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
                <span>{{ collapsed ? '' : item.title }}</span>
              </template>
              <!-- 子菜单项 -->
              <el-menu-item 
                v-for="child in item.children" 
                :key="child.menu.index" 
                :index="child.menu.index"
              >
                <el-icon v-if="child.menu.icon"><component :is="child.menu.icon" /></el-icon>
                <span>{{ collapsed ? '' : child.menu.title }}</span>
              </el-menu-item>
            </el-sub-menu>
            <!-- 普通菜单项 -->
            <el-menu-item v-else :index="item.index">
              <el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>
              <span>{{ collapsed ? '' : item.title }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      
      <!-- 右侧内容区域 -->
      <el-main class="app-content">
        <router-view v-slot="{ Component }" :key="route.path">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.app-container {
  height: 100vh;
  overflow: hidden;
}

.app-header {
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 0;
  z-index: 10;
}

.header-content {
  height: 100%;
  display: flex;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sidebar-toggle {
  margin-left: 20px;
}

.logo-text {
  margin: 0;
  font-size: 1.5rem;
  color: #667eea;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-right {
  text-align: right;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: flex-end;
  padding-right: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.username {
  color: #606266;
  font-weight: 500;
}

.main-container {
  height: calc(100vh - 60px);
  overflow: hidden;
}

.app-sidebar {
  background-color: #001529;
  transition: width 0.3s;
  overflow: hidden;
  min-width: 64px;
}

.app-sidebar.collapsed {
  width: 64px !important;
}

.sidebar-menu {
  height: 100%;
  border-right: none;
}

.app-content {
  background-color: #f5f7fa;
  padding: 20px;
  overflow-y: auto;
}

/* 页面切换动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
